package Leetcode.链表;

/**
 * @Author: kirito
 * @Description: TODO
 * @Date: 2024/2/25 12:46
 * @Version: 1.0
 */

public class 旋转链表 {
    /**
     * 1.k为链表长度整数倍时直接返回原链表即可
     * 2.可以先将链表连成环，然后循环在指定位置断开即可
     * @param head
     * @param k
     * @return
     */
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        int add = n - k % n;
        if (add == n) {
            return head;
        }
        //连成环
        iter.next = head;
        while (add-- > 0) {
            iter = iter.next;
        }
        ListNode ret = iter.next;
        iter.next = null;
        return ret;
    }
}
